package com.smbms.controller;

import com.smbms.pojo.User;
import com.smbms.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.sql.SQLException;
import java.util.List;

@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping("/login")
    public String login(User user, HttpSession session) throws SQLException {
        User user1 = userService.login(user);
        if (user1 != null) {
            session.setAttribute("user", user1);
            return "welcome";
        } else {
            return "redirect:/login.jsp";
        }
    }


    @GetMapping("/list")
    public String list(HttpSession session)throws Exception{
        List<User> users = userService.showAllList();
        for (User user:users)
            System.out.println(user.toString());
        session.setAttribute("userList",users);
        return "userList";
    }

    @PostMapping("/add")
    public String add(User user,HttpSession session)throws Exception{

        System.out.println(user);
        boolean isOK = userService.addUser(user);
        if(isOK){
            session.setAttribute("userList",userService.showAllList());
            return "userList";
        }else {
            return "userAdd";
        }
    }

    //添加responsebody，返回数据给前台
    @PostMapping("/del")
    @ResponseBody
    public boolean del(long id,HttpSession session)throws Exception{
        boolean isOK = userService.del(id);
       return isOK;
    }


    @GetMapping("/{id}")
    public String findById(@PathVariable Long id, Model model)throws  Exception{

        model.addAttribute("users",userService.showUserById(id));
        return "userView";
    }



    @GetMapping("/update/{id}")
    public String updateById(@PathVariable Long id, Model model) throws Exception{
        model.addAttribute("user",userService.showUserById(id));
        return "userUpdate";
    }


//保存修改后的数据
    @PostMapping("/{id}")
    public String saveUpdate(User user,@PathVariable long id,HttpSession session,Model model)throws Exception{
            user.setId(id);
        boolean isOK=userService.updateUser(user);
        if(isOK){
            session.setAttribute("userList",userService.showAllList());
            return "userList";

        }else {
            //修改不成功丢失原有数据，需要重新保存
            model.addAttribute("userList",userService.showUserById(id));
            return "userUpdate";
        }

    }

}
